<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Mod_pitrules extends MYAD_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('Mmod_pitcalcul','Pitcalcul');
         $this->load->model('Mmod_pitpara','Pitpara');
    }
    
    /**
     * @author Thanh NV        
     * @function index 
    
     * @This function show PIT Caculation Rules Registration
     */ 
    function index(){          
        $id= !empty($_POST['hidParameterID']) ? $_POST['hidParameterID'] : NULL;      
        //chose lang en or jp
        if(empty($id)) $id=$this->session->userdata('idPitRuleParameterID');
        $this->session->set_userdata('idPitRuleParameterID', $id);
        $data['title'] = $this->lang->line('h_PITrules');
        $data['show'] = "prindex";
        $this->load->library('pagination');             
        $total_data = $this->Pitcalcul->count_allID('ParameterId',$id); 
	$perpage	= 10;
        $data['pagination'] = $this->paginationData($total_data,$perpage,'/pit-rules');
        $offset = ($this->uri->segment(2)=='') ? 0 : $this->uri->segment(2);         
	$data['data'] = $this->Pitcalcul->listAllPaginationID($perpage, $offset,'ParameterId','ParameterId',$id);         
        
        $data['messsageError']=(count($data['data'])==0) ? $this->lang->line('CR_null') : "";
        $data['ParameterId']=$id;
        $data['page']=$offset;
        $this->load->view('layout',$data);
    }
    
    /**
     * @author Thanh NV        
     * @function addPitRules   
     * @This function add PIT Caculation Rules Registration
     */ 
    function addPitRules(){
        
        $pairs = explode('-',$this->input->post('hidParameterID')); 
//        var_dump($pairs); die;
            if ( is_array($pairs) && count($pairs)==2) {
                $parameterId=$pairs[0];
                $PITCalculationRuleId=$pairs[1];
            }else{
                $parameterId=$pairs[0];
                $PITCalculationRuleId=NULL;
            }   
        //    
        if(!is_null($PITCalculationRuleId))         
        {           // 
            $data=$this->Pitcalcul->listIdName('PITCalculationRuleId',$PITCalculationRuleId);

                if (!$data) {
                    redirect('/pit-rules/'.$parameterId);
                }

        }
        //
        if(!is_null($parameterId)) 
        {
            $data=$this->Pitpara->listIdName('ParameterId',$parameterId);

                if (!$data) {
                    redirect('/pit-parameter');
                }
        } 
        $data=array();
        if($this->input->post('btnButton')){ 
                $_POST['txtLevel'] = mb_convert_kana($_POST['txtLevel'], 'a');                
                $_POST['txtAssociatedAmount'] = mb_convert_kana($_POST['txtAssociatedAmount'], 'a');
                $_POST['txtRate'] = mb_convert_kana($_POST['txtRate'], 'a');                
                $this->load->library('form_validation');
                $this->form_validation->set_rules('txtLevel', $this->lang->line('pcrr__Level'), 'required|numeric|integer|greater_than[0]');                 
                $this->form_validation->set_rules('txtAssociatedAmount',$this->lang->line('pcrr__AssociatedAmount'), 'required|integer|greater_than[0]'); 
                $this->form_validation->set_rules('txtRate', $this->lang->line('pcrr__Rate'), 'required|callback_validate_float|greater_than[0]|less_than[100]'); 
                if($this->form_validation->run() == TRUE){
                    if(!is_null($PITCalculationRuleId)){
                         $data=array( 
                        'Upd_ID'=>$this->session->userdata('UserId'),
                        'Upd_Date'=>date("Y-m-d h:i:s"),     
                        'Del_Flag'=>($this->input->post('chkDelete')=='on') ? 1 : 0,       
                        'Level'=>$this->input->post('txtLevel'),
                        'ParameterId'=>$parameterId,     
                        'AssociatedAmount'=>$this->_str2number($this->input->post('txtAssociatedAmount')),
                        'Rate'=>$this->input->post('txtRate')/100,
                        );               
                    }else{
                        $data=array(                       
                        'Ins_ID'=>$this->session->userdata('UserId'),
                        'Ins_Date'=>date("Y-m-d h:i:s"),
                        'Upd_ID'=>$this->session->userdata('UserId'),
                        'Upd_Date'=>date("Y-m-d h:i:s"),     
                        'Del_Flag'=>($this->input->post('chkDelete')=='on') ? 1 : 0,       
                        'Level'=>$this->input->post('txtLevel'),
                        'ParameterId'=>$parameterId,     
                        'AssociatedAmount'=>$this->_str2number($this->input->post('txtAssociatedAmount')),
                        'Rate'=>$this->input->post('txtRate')/100,
                        );
                    }    
                   // $PITCalculationRuleId=$this->uri->segment(4);                    
                    if(is_null($PITCalculationRuleId)){                      
                        //Check Associated Amount max//
                        $arrCheckAssociatedAmount=$this->Pitcalcul->checkAssociatedAmount($parameterId,$data['AssociatedAmount']);                      
                        if($arrCheckAssociatedAmount['flag']==TRUE){                           
                                //Check Rate max 
                                $arrCheckRate=$this->Pitcalcul->checkRate($parameterId,$data['Rate']);  
                               
                                if($arrCheckRate['flag']){  
                                    $arrLevelConditions=array('Level'=>$data['Level'],'ParameterId'=>$data['ParameterId']);
                                    
                                    if(!$this->Pitcalcul->listWhere($arrLevelConditions)){
                                        
                                        $result =$this->Pitcalcul->insertData($data);                         
                                        if($result){                       
                                            $data= array(
                                                   'flag' => TRUE,
                                                   'message' => $this->lang->line('emp_updateDB_success')
                                               );  
                                       }else{
                                            $data=array(
                                                       'flag' => FALSE,
                                                       'message' => $this->lang->line('emp_updateDB_fall')
                                                   );
                                        }
                                    }else{                                       
                                        redirect('/pit-rules/add/'.$parameterId);
                                    }   
                                }else{
                                    $data=$this->Pitcalcul->checkRate($parameterId,$data['Rate']);
                                } 
                                //End check rate
                        }else{                           
                           $data=$this->Pitcalcul->checkAssociatedAmount($parameterId,$data['AssociatedAmount']);
                        }
                        //End check Amount
                    }else{   
                        //Check Amount 
                        $arrCheckAssociatedAmount=$this->Pitcalcul->checkAssociatedAmountLevel($parameterId,$data['AssociatedAmount'],$data['Level']);                      
                        if($arrCheckAssociatedAmount['flag']==TRUE){                           
                            //Check Rate
                                $arrCheckRate=$this->Pitcalcul->checkRateLevel($parameterId,$data['Rate'],$data['Level']);                      
                                if($arrCheckRate['flag']){
                                        $result =$this->Pitcalcul->updateDataName($data, $PITCalculationRuleId, 'PITCalculationRuleId');
                                        if($result){                       
                                                $data= array(
                                                       'flag' => TRUE,
                                                       'message' => $this->lang->line('emp_updateDB_success')
                                                   );  
                                           }else{
                                                $data=array(
                                                           'flag' => FALSE,
                                                           'message' => $this->lang->line('emp_updateDB_fall')
                                                       );
                                            }
                                }else{
                                        $data=$this->Pitcalcul->checkRateLevel($parameterId,$data['Rate'],$data['Level']);
                                }    
                                //End check Rate
                        }else{
                                $data=$this->Pitcalcul->checkAssociatedAmountLevel($parameterId,$data['AssociatedAmount'],$data['Level']);
                        }
                        $data['Del_Flag']=($this->input->post('chkDelete')=='on') ? 1 : 0;
                        //End check Amount
                    }
                        
                        $data['PITCalculationRuleId']=$PITCalculationRuleId;
                }   
                $data['Level']=$this->input->post('txtLevel');
                $data['AssociatedAmount']=$this->input->post('txtAssociatedAmount');  
                if(($this->input->post('txtRate')!="") && check_float_string($this->input->post('txtRate'))){
                     $data['Rate']=$this->input->post('txtRate')/100 ;
                }elseif(($this->input->post('txtRate')!="") && !check_float_string($this->input->post('txtRate'))){
                    $data['Rate']= $this->input->post('txtRate');
                }else{
                    $data['Rate']="";
                }
                
        } else{                       
//                $PITCalculationRuleId=$this->uri->segment(4);    
                $data['Level']=$this->Pitcalcul->checkLevel($parameterId);
                if(isset($PITCalculationRuleId) && !empty($PITCalculationRuleId)) $data=$this->Pitcalcul->listIdName('PITCalculationRuleId',$PITCalculationRuleId);
                
               } 
        $data['ParameterId']=$parameterId;       
        if(!empty($PITCalculationRuleId) && !is_null($PITCalculationRuleId)){ 
            $data['title'] = $this->lang->line('pcrr__Title_update');    
        }else{
            $data['title'] = $this->lang->line('pcrr__Title');    
        }    
        $data['dialogTitle']=$this->lang->line('emp_dialog_title');    
        $data['js'] = array('jquery-ui.js','jquery.number.js');
	$data['css'] = array('jquery-ui.css');        
        $data['show'] = "add_pitrules";                
        $this->load->view('layout',$data);		
	}
           //
        
           /**
        * @author Thanh NV        
        * @created:2014/06/23
        * @function _str2number 
        * @param: str
        * @Output: int
        * @This function return string to number
        */ 
           function _str2number($inputData=''){
	  $outputData = '';
	  if (is_array($inputData)) {
	   foreach ($inputData as $k => $v) {
		$outputData[trim($k)] = (float)str_replace(',','',trim($v));
	   }
	  }else $outputData = (float)str_replace(',','',trim($inputData));
	  return $outputData;
	 }
         
         //
         
             /**
        * @author Thanh NV        
        * @function validate_date 
        * @param: $float or $int
        * Output: TRUE or FALSE
        * @This function check validate float
        */
       public function validate_float($float = NULL) {  
          $float=  isset($_POST['txtRate']) ? $_POST['txtRate'] : NULL;
               if(check_float_string($float)){ 
                   return TRUE;
               } else {
                   $this->form_validation->set_message('validate_float', '%s ' . $this->lang->line('MC014'));
                   return FALSE;
               }
       }

}
?>